/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.util.iterators;

import java.util.Arrays;
import java.util.NoSuchElementException;

/** Iterator that returns all strings of a given length. */
public class StringIterator extends LexicographicalIterator {

	private int length;
	private int alphabetSize;
	private int[] next;
	private int nextLeftmostChangedPos;
	private int[] current;
	private int leftmostChangedPos;
	
	public StringIterator(int alphabetSize, int length) {
		this.length = length;
		this.alphabetSize = alphabetSize;
		next = new int[length];
		current = null;
		nextLeftmostChangedPos = 0;
		leftmostChangedPos = -1;
	}
	
	@Override
	public int getLeftmostChangedPosition() {
		if (current==null) throw new IllegalStateException();
		return leftmostChangedPos;
	}

	@Override
	public int getStringLength() {
		return length;
	}

	@Override
	public int[] peek() {
		if (next==null) throw new NoSuchElementException();
		return next;
	}

	private void step(int skipPosition) {
		int i = skipPosition;
		while ((i>=0) && (next[i]==alphabetSize-1)) i-=1;
		if (i<0) {
			next = null;
			return;
		}
		nextLeftmostChangedPos = i;
		next[i++] += 1;
		Arrays.fill(next, i, next.length, 0);
	}
	
	@Override
	public void skip(int position) {
		if (next == null) return;
		if (nextLeftmostChangedPos<=position) return;
		step(position);
	}

	@Override
	public boolean hasNext() {
		return next!=null;
	}

	@Override
	public int[] next() {
		if (next==null) throw new NoSuchElementException();
		current = Arrays.copyOf(next, next.length);
		leftmostChangedPos = nextLeftmostChangedPos;
		step(length - 1);
		return current;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

}
